#include "XformParser.h"

#include "BoolParser.h"
#include "DoubleParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

XformParser::XformParser(
    DoubleParser *&_xOffsetParser
    , DoubleParser *&_yOffsetParser
    , DoubleParser *&_rotationParser
    , BoolParser *&_mirrorParser
    , DoubleParser *&_scaleParser
):    m_xOffsetParser(_xOffsetParser)
    , m_yOffsetParser(_yOffsetParser)
    , m_rotationParser(_rotationParser)
    , m_mirrorParser(_mirrorParser)
    , m_scaleParser(_scaleParser)
{

}

bool XformParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new Xform());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("xOffset")))
    {
        data = reader->attributes().value(QStringLiteral("xOffset"));
        if (!m_xOffsetParser->parse(reader, data))
            return false;
        m_result->xOffsetOptional = Optional<Double>(m_xOffsetParser->result());
    }
    if (reader->attributes().hasAttribute(QStringLiteral("yOffset")))
    {
        data = reader->attributes().value(QStringLiteral("yOffset"));
        if (!m_yOffsetParser->parse(reader, data))
            return false;
        m_result->yOffsetOptional = Optional<Double>(m_yOffsetParser->result());
    }
    if (reader->attributes().hasAttribute(QStringLiteral("rotation")))
    {
        data = reader->attributes().value(QStringLiteral("rotation"));
        if (!m_rotationParser->parse(reader, data))
            return false;
        m_result->rotationOptional = Optional<Double>(m_rotationParser->result());
    }
    if (reader->attributes().hasAttribute(QStringLiteral("mirror")))
    {
        data = reader->attributes().value(QStringLiteral("mirror"));
        if (!m_mirrorParser->parse(reader, data))
            return false;
        m_result->mirrorOptional = Optional<Bool>(m_mirrorParser->result());
    }
    if (reader->attributes().hasAttribute(QStringLiteral("scale")))
    {
        data = reader->attributes().value(QStringLiteral("scale"));
        if (!m_scaleParser->parse(reader, data))
            return false;
        m_result->scaleOptional = Optional<Double>(m_scaleParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

Xform *XformParser::result()
{
    return m_result.take();
}

}